import React from 'react';
import {Button, Empty, Form, Modal, Popconfirm, Table, Toast, Tooltip,} from '@douyinfe/semi-ui';
import {IllustrationNoContent, IllustrationNoContentDark,} from '@douyinfe/semi-illustrations';

import classifyStyle from './index.less';
import categoryAPI from '@/api/model/category';

const {Column} = Table;

export default class Classify extends React.Component {
    private formApi: any;

    constructor(props: any) {
        super(props);
        this.state = {
            // @ts-ignore
            tableLoading: false,
            isCreate: true,
            visible: false,
            saveLoading: false,
            pagination: {
                page_size: 10,
                page_current: 1,
                total: 0,
            },
            data: [],
            formData: {},
        };
        this.showDialog = this.showDialog.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.updatebooktype = this.updatebooktype.bind(this);
        this.handlePageChange = this.handlePageChange.bind(this);
    }

    showDialog() {
        this.setState({
            visible: true,
            isCreate: true,
        });
    }

    handleCancel() {
        this.setState({
            visible: false,
        });
    }

    componentDidMount() {
        this.getCategorylist();
    }

    async updatebooktype() {
        await this.setState({
            visible: true,
            isCreate: false,
        });
        const {formData}: any = this.state
        await this.formApi.setValue('name', formData.name);
        await this.formApi.setValue('icon', formData.icon);
        await this.formApi.setValue('sort', formData.sort);
        await this.formApi.setValue('id', formData.id);
    }

    // 获取分类列表
    async getCategorylist() {
        this.setState({
            tableLoading: true,
        });
        const {pagination}: any = this.state;
        const res = await categoryAPI.categoryList(pagination);
        this.setState({
            data: res.data.data,
            tableLoading: false,
            pagination: {
                ...pagination,
                total: res.data.total,
            },
        });
    }

    async handleSubmit(e: any) {
        const {isCreate}: any = this.state;
        this.setState({
            saveLoading: true,
        });
        let res: any = {};
        if (isCreate) {
            res = await categoryAPI.CreateCategory(e);
        } else {
            res = await categoryAPI.UpdateCategory(e);
        }

        if (res.status) {
            Toast.success({
                content: `${isCreate ? '创建' : '修改'}书签分类成功！`,
                duration: 3,
            });
            setTimeout(async () => {
                await this.getCategorylist();
                this.setState({
                    visible: false,
                    saveLoading: false,
                });
            }, 350);
        } else {
            this.setState({
                visible: false,
                saveLoading: false,
            });
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }

    async handlePageChange(page_current: number) {
        const {pagination}: any = this.state;
        await this.setState({
            pagination: {
                ...pagination,
                page_current,
            },
        });
        await this.getCategorylist();
    }

    async delBookType() {
        const {formData}: any = this.state;
        const res = await categoryAPI.DelCategory({id: formData.id});
        if (res.status) {
            Toast.success({
                content: `删除成功！`,
                duration: 3,
            });
            await this.getCategorylist();
        } else {
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }

    getFormApi(formApi: any) {
        this.formApi = formApi;
    }

    render() {
        const {
            data,
            visible,
            formData,
            isCreate,
            saveLoading,
            pagination,
            tableLoading,
            modalVisible,
        }: any = this.state;
        const emptyStyle = {
            padding: 30,
        };
        return (
            <div
                className={[classifyStyle.classify_container, 'content_container'].join(
                    ' ',
                )}
            >
                <Button
                    onClick={this.showDialog}
                    style={{marginBottom: '1rem'}}
                    theme="light"
                    type="secondary"
                >
                    新增书签分类
                </Button>
                <Table
                    empty={
                        <Empty
                            image={
                                <IllustrationNoContent style={{width: 150, height: 150}}/>
                            }
                            darkModeImage={
                                <IllustrationNoContentDark
                                    style={{width: 150, height: 150}}
                                />
                            }
                            description={'暂无内容，请添加'}
                            style={emptyStyle}
                        />
                    }
                    bordered
                    dataSource={data}
                    loading={tableLoading}
                    onRow={(record, index) => {
                        return {
                            onClick: (event) => {
                                this.setState({
                                    formData: record,
                                });
                            },
                        };
                    }}
                    pagination={{
                        currentPage: pagination.page_current,
                        pageSize: pagination.page_size,
                        total: pagination.total,
                        onPageChange: this.handlePageChange,
                    }}
                >
                    <Column title="id" dataIndex="id" key="id"/>
                    <Column title="分类名称" dataIndex="name" key="name"/>
                    <Column
                        title="排序"
                        dataIndex="sort"
                        key="sort"
                        sorter={(a: { sort: number }, b: { sort: number }) =>
                            a.sort - b.sort > 0 ? 1 : -1
                        }
                    />
                    <Column
                        title="创建时间"
                        dataIndex="create_time"
                        key="create_time"
                        sorter={(a: { create_time: any }, b: { create_time: any }) =>
                            a.create_time - b.create_time > 0 ? 1 : -1
                        }
                    />
                    <Column
                        title="更新时间"
                        dataIndex="updated_time"
                        key="updated_time"
                    />
                    <Column
                        title=""
                        render={() => {
                            return (
                                <>
                                    <Tooltip content={'修改书签分类'}>
                                        <Button
                                            onClick={this.updatebooktype}
                                            theme="light"
                                            type="secondary"
                                            style={{marginRight: 8}}
                                        >
                                            修改
                                        </Button>
                                    </Tooltip>
                                    <Popconfirm
                                        content="是否确认删除"
                                        onConfirm={() => this.delBookType()}
                                    >
                                        <span style={{display: 'inline-block'}}>
                                          <Tooltip content={'删除书签分类'}>
                                            <Button
                                                theme="light"
                                                type="danger"
                                                style={{marginRight: 8}}
                                            >
                                              删除
                                            </Button>
                                          </Tooltip>
                                        </span>
                                    </Popconfirm>
                                </>
                            );
                        }}
                    />
                </Table>
                <ModalForm
                    showDialog={this.showDialog}
                    getFormApi={(e: any) => this.getFormApi(e)}
                    saveLoading={saveLoading}
                    formData={formData}
                    isCreate={isCreate}
                    visible={visible}
                    handleCancel={this.handleCancel}
                    handleSubmit={(e: any) => this.handleSubmit(e)}
                />
            </div>
        );
    }
}

const ModalForm = (props: any) => {
    return (
        <>
            <Modal
                title={props.isCreate ? '新建' : '编辑'}
                visible={props.visible}
                onCancel={props.handleCancel}
                className="modalStyle"
                centered
                footer={''}
            >
                <div style={{paddingBottom: '1rem'}}>
                    <Form
                        getFormApi={props.getFormApi}
                        onSubmit={(values) => props.handleSubmit(values)}
                        style={{width: 400}}
                    >
                        {({formState, values, formApi}) => (
                            <>
                                <Form.Input
                                    rules={[{required: true, message: '请输入分类名称'}]}
                                    field="name"
                                    label="分类名称"
                                    style={{width: '100%'}}
                                    placeholder="请输入分类名称"
                                />
                                <Form.Input
                                    field="sort"
                                    label="排序"
                                    style={{width: '100%'}}
                                    placeholder="请输入排序"
                                />
                                <div style={{display: 'flex', justifyContent: 'flex-end'}}>
                                    <Button
                                        htmlType="submit"
                                        type="tertiary"
                                        loading={props.saveLoading}
                                    >
                                        提 交
                                    </Button>
                                </div>
                            </>
                        )}
                    </Form>
                </div>
            </Modal>
        </>
    );
};
